package com.gin.no_gay_alliance.worker;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.work.BackoffPolicy;
import androidx.work.Constraints;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import androidx.work.WorkRequest;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.gin.no_gay_alliance.app.MyApplication;

import java.util.concurrent.TimeUnit;

/**
 * 更新提醒消息工作
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/22 12:10
 **/
public class UpdateNoticeWorker extends Worker {
    private static final String TAG = UpdateNoticeWorker.class.getSimpleName();

    public UpdateNoticeWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        Log.d(TAG, "[提醒消息] 检查提醒消息");
        // 更新提醒消息
        MyApplication.app.managerFactory.getNoticeManager().updateData(null);
        startWorker(5);
        return Result.success();
    }

    public static void startWorker(long delayMinutes) {
        WorkManager workManager = WorkManager.getInstance(MyApplication.app);
        // 清空之前的任务
        workManager.cancelAllWorkByTag(UpdateNoticeWorker.class.getName());
        // 提交任务
        workManager.enqueue(buildWorkRequest(delayMinutes));
    }

    /**
     * 创建工作请求
     *
     * @return 工作请求
     */
    public static WorkRequest buildWorkRequest(long delayMinutes) {
        // 连上网络才执行
        Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();

        return new OneTimeWorkRequest.Builder(UpdateNoticeWorker.class)
                .setConstraints(constraints)
                .setInitialDelay(delayMinutes, TimeUnit.MINUTES)
                // 重试策略
                .setBackoffCriteria(BackoffPolicy.LINEAR, OneTimeWorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
                .build();
    }
}
